<template>
    <div>
      <!--面包屑导航区-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>商品分类</el-breadcrumb-item>
      </el-breadcrumb>
    <el-card class="box-card">
      <!--搜索与添加区-->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="addDialogShow()">添加分类</el-button>
        </el-col>
      </el-row>
    </el-card>
      <tree-table :data="categoriesList" :columns="columns" :selection-type="false"
      :expand-type="false" show-index index-text="#" border :show-row-hover="false">
        <!-- 自定义列 是否有效 -->
        <template slot="isOk" slot-scope="scope">
          <i class="el-icon-success" style="color:lightgreen" v-if="scope.row.cat_deleted === false"></i>
          <i class="el-icon-error" style="color:lightgreen" v-else></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag v-else-if="scope.row.cat_level === 1" type="success">二级</el-tag>
          <el-tag v-else type="danger">三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="getCateById(scope.row.cat_id)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteCateById(scope.row.cat_id)">删除</el-button>
        </template>
      </tree-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <!-- 添加分类 -->
      <el-dialog title="添加分类" :visible.sync="addDialogVisible" width="50%" @close="addDilogClose()">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类">
            <el-cascader v-model="selectedKeys"
            :options="parentCateList"
            :props="cascaderProps"
            @change="handleChange">
            </el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDilogClose()">取 消</el-button>
          <el-button type="primary" @click="addCat()">确 定</el-button>
        </span>
      </el-dialog>
    <!-- 编辑分类 -->
     <el-dialog title="编辑分类" :visible.sync="eidtDialogVisible" width="50%" @close="editDilogClose()">
      <el-form :model="editForm" ref="editFormRef" label-width="80px">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDilogClose()">取 消</el-button>
        <el-button type="primary" @click="editCat()">确 定</el-button>
      </span>
    </el-dialog>
    </div>
</template>

<script>
export default {
  data () {
    return {
      // 商品分类列表
      categoriesList: [],
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      total: 0,
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          // 自定义列
          type: 'template',
          template: 'isOk'
        },
        {
          label: '排序',
          // 自定义列
          type: 'template',
          template: 'order'
        },
        {
          label: '操作',
          // 自定义列
          type: 'template',
          template: 'opt'
        }
      ],
      addDialogVisible: false,
      addForm: {
        cat_name: '',
        cat_level: 0,
        cat_pid: 0
      },
      addFormRules: {},
      // 保存父级分类数据
      parentCateList: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        // 选择任意一项
        checkStrictly: true
      },
      // 选中的级联的数据
      selectedKeys: [],
      // 编辑分类相关操作
      eidtDialogVisible: false,
      editForm: {}
    }
  },
  created () {
    this.getCategoriesList()
  },
  methods: {
    // 获取商品分类列表
    async getCategoriesList () {
      const { data: res } = await this.$http.get('categories', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.error('获取列表数据据失败')
      this.categoriesList = res.data.result
      this.total = res.data.total
    },
    // 每页显示数据改变触发的事件
    handleSizeChange (newPageSize) {
      this.queryInfo.pagesize = newPageSize
      this.getCategoriesList()
    },
    // 页数切换触发的事件
    handleCurrentChange (newCurrent) {
      this.queryInfo.pagenum = newCurrent
      this.getCategoriesList()
    },
    // 添加商品分类
    async addCat () {
      console.log(this.addForm)
      const { data: res } = await this.$http.post('categories', this.addForm)
      if (res.meta.status !== 201) return this.$message.error('创建商品分类失败')
      this.$message.success(res.meta.msg)
      this.getCategoriesList()
      this.addDialogVisible = false
    },
    addDialogShow () {
      // 获取级联数据
      this.getParentCateList()
      this.addDialogVisible = true
    },
    // 获取父级的分类列表
    async getParentCateList () {
      const { data: res } = await this.$http.get('categories', { params: { type: 3 } })
      if (res.meta.status !== 200) return this.$message.error('获取父级分类失败')
      console.log(res)
      this.parentCateList = res.data
      console.log(this.parentCateList)
    },
    handleChange () {
      // 商品父级分类cat_pid为选中项的最后一项
      if (this.selectedKeys.length > 0) {
        this.addForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
        this.addForm.cat_level = this.selectedKeys.length
        console.log(this.selectedKeys)
      } else {
        this.addForm.cat_pid = 0
        this.addForm.cat_level = 0
      }
    },
    // 添加分类框关闭事件
    addDilogClose () {
      this.$refs.addFormRef.resetFields()
      this.selectedKeys = []
      this.addForm.cat_pid = 0
      this.addForm.cat_level = 0
    },
    // 根据id获取对应的分类数据
    async getCateById (id) {
      const { data: res } = await this.$http.get(`categories/${id}`)
      if (res.meta.status !== 200) return this.$message.error('获取分类失败')
      this.eidtDialogVisible = true
      this.editForm = res.data
    },
    // 编辑分类数据并保存
    async editCat () {
      const { data: res } = await this.$http.put(`categories/${this.editForm.cat_id}`, { cat_name: this.editForm.cat_name })
      if (res.meta.status !== 200) return this.$message.error('更新数据失败')
      this.getCategoriesList()
      this.$message.success(res.meta.msg)
      this.eidtDialogVisible = false
    },
    // 根据id删除单个分类
    async deleteCateById (id) {
      const confirmRes = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => { return err })
      if (confirmRes !== 'confirm') return this.$message.error('取消了删除操作')
      const { data: res } = await this.$http.delete(`categories/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除分类失败')
      this.getCategoriesList()
      this.$message.success('删除分类成功')
    },
    // 编辑分类窗口关闭事件
    editDilogClose () {
      this.$refs.editFormRef.resetFields()
      this.eidtDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 5px;
}
.tbtop {
  border-top: 1px solid #eee
}
.tbbottom {
  border-bottom: 1px solid #eee
}
.tagmiddle {
  display: flex;
  align-items: center;
}
.el-cascader{
    width: 100%;
}
</style>
